package com.xbongbong.paas.help.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.admin.pojo.dto.MirrorRollBackDTO;
import com.xbongbong.admin.pojo.vo.MirrorRollBackVO;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.BusinessRuleInfoEntity;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.BIProductEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.LowCodeHelp;
import com.xbongbong.paas.manager.feign.MirrorFeignClent;
import com.xbongbong.paas.model.BusinessRuleInfoModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.pojo.dto.FormEntityUpdateDTO;
import com.xbongbong.paas.pojo.dto.FormExplainAddDTO;
import com.xbongbong.paas.pojo.dto.MenuFormAddDTO;
import com.xbongbong.paas.pojo.dto.MenuGroupAddDTO;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.PaasMenuService;
import com.xbongbong.paas.service.init.AbstractInitMenuHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.MarketManagementMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.form.pojo.dto.FormAddBatchDTO;
import com.xbongbong.pro.form.pojo.dto.FormUpdateBatchDTO;
import com.xbongbong.pro.form.pojo.vo.FormAddBatchVO;
import com.xbongbong.pro.formexplain.pojo.dto.FormExplainAddBatchDTO;
import com.xbongbong.pro.formexplain.pojo.vo.FormExplainAddBatchVO;
import com.xbongbong.pro.fundset.pojo.FundSetTransitionPojo;
import com.xbongbong.pro.menu.pojo.dto.MenuFormAddBatchDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuGroupAddBatchDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.menu.pojo.vo.MenuFormAddBatchVO;
import com.xbongbong.pro.menu.pojo.vo.MenuGroupAddBatchVO;
import com.xbongbong.pro.menu.pojo.vo.MenuInitVO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.saas.service.StageInitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author long
 * @version v1.0
 * @date 2020/11/3 10:10
 * @since v1.0
 */
@Component
public class InitMarketManagementHelp extends AbstractInitMenuHelp {

    private static final Logger LOG = LoggerFactory.getLogger(InitMarketManagementHelp.class);

    @Resource
    private PaasMenuService paasMenuService;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private MirrorFeignClent mirrorFeignClent;
    @Resource
    private BusinessRuleInfoModel businessRuleInfoModel;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private StageInitService stageInitService;
    @Resource
    private LowCodeHelp lowCodeHelp;

    @Override
    public List<String> alias() {
        return Arrays.asList(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias());
    }
    @Override
    public MenuInitVO initApp(MenuInitDTO menuInitDTO, Map<String, PaasAppEntity> appMap) throws XbbException {
        return initMenu(menuInitDTO, appMap);
    }

    @Override
    public MenuInitVO initMenu(MenuInitDTO menuInitDTO, Map<String, PaasAppEntity> appMap) throws XbbException {
        MenuInitVO menuInitVO = new MenuInitVO();
        try {
            // 获取下应用id
            menuInitDTO.setAppId(menuInitDTO.getAppMap().get(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias()).getId());

            // 插入菜单分组
            MenuGroupAddBatchVO marketGroupAddBatchVO = groupAddBatch(menuInitDTO);
            if(Objects.isNull(marketGroupAddBatchVO)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 插入除分组外对应的菜单
            MenuFormAddBatchVO menuFormAddBatchVO = formAddBatch(menuInitDTO, marketGroupAddBatchVO);
            if (Objects.isNull(menuFormAddBatchVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            List<PaasMenuEntity> menuGroupList = marketGroupAddBatchVO.getMenuList();
            List<PaasMenuEntity> menuFormList = menuFormAddBatchVO.getMenuList();
            List<PaasMenuEntity> menuList = new ArrayList<>();
            menuList.addAll(menuGroupList);
            menuList.addAll(menuFormList);
            // 插入菜单对应的表单
            FormAddBatchDTO formAddBatchDTO = new FormAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, formAddBatchDTO);
            List<FormEntityAddDTO> formList = new ArrayList<>();
            // 通过分组菜单，得到需要插入的表单列表
            getFormList(formList, menuList);
            formAddBatchDTO.setFormList(formList);
            FormAddBatchVO formAddBatchVO = paasFormService.addBatch(formAddBatchDTO);
            if (Objects.isNull(formAddBatchVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 插入表单对应的字段解释
            formExplainAddBatch(menuInitDTO, formAddBatchVO);
            menuInitVO.setFormList(formAddBatchVO.getFormList());
            // 线索表单需要初始化阶段
            formAddBatchVO.getFormList().forEach(form -> {
                Integer businessType = form.getBusinessType();
                boolean needInitStage = Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType);
                if (needInitStage) {
                    stageInitService.init(form.getCorpid(), businessType, form.getId());
                }
            });
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.initMenu初始化菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuInitVO;
    }


    @Override
    public void rollBackInit(MirrorRollBackDTO mirrorRollBackDTO, List<Long> systemFormList, PaasFormEntity paasProductFormEntity) throws XbbException {
        String targetCorpid = mirrorRollBackDTO.getTargetCorpid();
        Long appId = mirrorRollBackDTO.getAppId();
        try {
            // 1. 根据安装的系统表单反推菜单
            HashSet<Long> menuIds = new HashSet<>();
            HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", targetCorpid);
            param.put("appId", appId);
            param.put("idIn", systemFormList);
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasFormEntity> sysInstallFormList = paasFormModel.findEntity(param);
            sysInstallFormList.forEach(item -> {
                menuIds.add(item.getMenuId());
            });
            // 2. 根据菜单找所有表单
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("appId", appId);
            param.put("menuIdIn", menuIds);
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasFormEntity> paasFormList = paasFormModel.findEntity(param);
            HashSet<Long> formIds = new HashSet<>();
            paasFormList.forEach(item -> {
                formIds.add(item.getId());
            });
            // 校验是否有数据
            newCheckData(mirrorRollBackDTO);

            // 3. 回退菜单
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("appId", appId);
            param.put("idOrParentIdIn", menuIds);
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasMenuEntity> paasMenuList = paasMenuModel.findEntitys(param);
            updateInitMenu(paasMenuList, targetCorpid);

            // 4. 回退表单
            List<FormEntityUpdateDTO> formList = new ArrayList<>();
            HashMap<Long,PaasFormEntity> systemPaasForms =new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            PaasFormEntity retainPaasFormEntity = new PaasFormEntity();
            List<Long> delFormIds = new ArrayList<>();
            Integer customNum = 0;
            Integer contract = 0;
            Integer saleOpportunity = 0;
            for (PaasFormEntity paasFormEntity : paasFormList) {
                FormEntityUpdateDTO formEntityUpdateDTO = new FormEntityUpdateDTO();

                if (Objects.equals(paasFormEntity.getBusinessType(), XbbRefTypeEnum.CLUE.getCode())) {
                    // 线索只会有删除操作
                    if (contract == 0) {
                        contract++;
                    } else {
                        paasFormEntity.setDel(DelEnum.DELETE.getDel());
                        delFormIds.add(paasFormEntity.getId());
                        contract++;
                    }
                }
                BeanUtil.copyProperties(paasFormEntity, formEntityUpdateDTO);
                formList.add(formEntityUpdateDTO);
                systemPaasForms.put(paasFormEntity.getId(), paasFormEntity);
            }
            // 更新表单到初始化
            getUpdateFormList(formList);
            FormUpdateBatchDTO formUpdateBatchDTO = new FormUpdateBatchDTO();
            formUpdateBatchDTO.setCorpid(targetCorpid);
            formUpdateBatchDTO.setFormList(formList);
            formUpdateBatchDTO.setCompanyInit(1);
            // 回退表单
            paasFormService.updateBatch4Mirror(formUpdateBatchDTO);
            // 3. 表单解释
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("appId", appId);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("formIdIn", formIds);
            param.put("saasMark", SaasMarkEnum.SAAS.getCode());
            List<PaasFormExplainEntity> paasFormExplainEntityList = paasFormExplainModel.findEntitys(param);
            formExplainUpdateBatch(paasProductFormEntity, paasFormExplainEntityList, mirrorRollBackDTO.getTargetCorpid(),systemPaasForms,delFormIds);

            /*// 更新应用信息(待定)
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(mirrorRollBackDTO.getAppId(), mirrorRollBackDTO.getTargetCorpid());
            SystemAppMenuEnum systemAppMenuEnum = SystemAppMenuEnum.getSystemAppMenuEnum(mirrorRollBackDTO.getAlias());
            AccessLinkEnum accessLinkEnum = systemAppMenuEnum.getAccessLinkEnum();
            paasAppEntity.setIcon(accessLinkEnum.getIcon());
            paasAppEntity.setColor(accessLinkEnum.getColor());
            paasAppEntity.setName(systemAppMenuEnum.getName());
            paasAppModel.update(paasAppEntity);*/

            //更新打印模板
            // rollBackToDefaultPrintTemplates(targetCorpid,appId,paasFormList,mirrorRollBackDTO.getAlias(),delFormIds);

            // 初始化时是没有业务规则的，所以删除表单对应的所有业务规则
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("appId", appId);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("formIdIn", formIds);
            param.put("saasMark", SaasMarkEnum.SAAS.getCode());
            List<BusinessRuleInfoEntity> ruleInfoEntityList = businessRuleInfoModel.findEntitys(param);
            Set<Long> ruleIdSets = new HashSet<>();
            ruleInfoEntityList.forEach(item -> ruleIdSets.add(item.getId()));
            List<Long> ruleIdIn = new ArrayList<>(ruleIdSets);
            if (ruleIdIn.size() > 0) {
                businessRuleInfoModel.deleteBatch(ruleIdIn, targetCorpid);
            }
            // 标签初始化
            labelHelp.deleteAllAndinit(paasFormList, targetCorpid, appId);

            // 初始化时没有低代码，此处删除所有低代码及配置
            lowCodeHelp.deleteLowCode(targetCorpid, formIds);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.menuInit初始化菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 回退到初始化解释
     * @param paasProductFormEntity
     * @param paasFormExplainEntityList
     * @param corpid
     * @param systemPaasForms
     * @return
     * @throws XbbException
     */
    public List<PaasFormExplainEntity> formExplainUpdateBatch(PaasFormEntity paasProductFormEntity,List<PaasFormExplainEntity> paasFormExplainEntityList ,String corpid,HashMap<Long, PaasFormEntity> systemPaasForms,List<Long> delFormIds) throws XbbException {
        try {
            for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainEntityList) {
                if (delFormIds.contains(paasFormExplainEntity.getFormId())){
                    paasFormExplainEntity.setDel(DelEnum.DELETE.getDel());
                }else{
                    // 过滤掉bi的一些表单
                    BIProductEnum biProductEnum = BIProductEnum.getByCode(paasFormExplainEntity.getBusinessType());
                    if (Objects.nonNull(biProductEnum) ||
                            Objects.equals(paasFormExplainEntity.getBusinessType(), XbbRefTypeEnum.CONTRACT_PERFORMANCE.getCode())) {
                        continue;
                    }
                    String alias = XbbRefTypeEnum.getByCode(paasFormExplainEntity.getBusinessType()).getAlias();
                    List<FieldAttrEntity> fieldAttrEntities=new ArrayList<>();
                    MarketManagementMenuEnum crmMenuEnum = MarketManagementMenuEnum.getByAlias(alias);
                    if (Objects.nonNull(crmMenuEnum)){
                        FundSetTransitionPojo fundSetTransitionPojo = new FundSetTransitionPojo(corpid);
                        if (StringUtil.isNotEmpty(crmMenuEnum.getParent())){
                            fieldAttrEntities=(InitExplainsHelper.initFieldAttrEntity(crmMenuEnum.getParent(),paasProductFormEntity, fundSetTransitionPojo, DistributorMarkEnum.OTHER.getCode()));
                        }else{
                            fieldAttrEntities=(InitExplainsHelper.initFieldAttrEntity(alias,paasProductFormEntity, fundSetTransitionPojo, DistributorMarkEnum.OTHER.getCode()));
                        }
                    }
                    paasFormExplainEntity.setExplains(JSON.toJSONString(fieldAttrEntities));
                }
            }
            paasFormExplainModel.updateBatch(paasFormExplainEntityList,corpid);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitCrmMenuHelp.formExplainUpdateBatch批量添加表单解释信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return paasFormExplainEntityList;
    }

    public Boolean newCheckData(MirrorRollBackDTO mirrorRollBackDTO) throws XbbException{
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        XbbResponse<MirrorRollBackVO> mirrorRollBackVOXbbResponse = mirrorFeignClent.checkData(mirrorRollBackDTO, lang);
        if (mirrorRollBackVOXbbResponse.isSuccess()) {
            return true;
        } else {
            throw new XbbException(mirrorRollBackVOXbbResponse.getCode(), mirrorRollBackVOXbbResponse.getMsg());
        }
    }


    /**
     * 更新表单到初始化
     * @param formList
     * @return
     * @throws XbbException
     */
    private List<FormEntityUpdateDTO> getUpdateFormList(List<FormEntityUpdateDTO> formList) throws XbbException{
        for (FormEntityUpdateDTO formEntityAddDTO : formList) {
            if (Objects.equals(formEntityAddDTO.getDel(),DelEnum.NORMAL.getDel())) {
                MarketManagementMenuEnum formEnum = MarketManagementMenuEnum.getByCode(formEntityAddDTO.getBusinessType());
                // CRMMenuEnum formEnum = CRMMenuEnum.getByCode(formEntityAddDTO.getBusinessType());
                formEntityAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                formEntityAddDTO.setLabels(getAppDefaultLabel(formEnum.getCode()));
                formEntityAddDTO.setCustomTitle(getAppDefaultTitle(formEnum.getCode()));
                formEntityAddDTO.setSummary(getAppDefaultSummary(formEnum.getCode()));
                formEntityAddDTO.setBusinessRules("0");
                // formList.add(formEntityAddDTO);
            }
        }
        return formList;
    }
    /**
     * 修改菜单到初始化状态

     * @return
     * @throws XbbException
     */
    private void updateInitMenu(List<PaasMenuEntity> paasMenuEntites,String corpid) throws XbbException {
        try {
            for (PaasMenuEntity paasMenuEntite : paasMenuEntites) {
                MarketManagementMenuEnum menuEnum = MarketManagementMenuEnum.getByAlias(paasMenuEntite.getAlias());
                // CRMMenuEnum menuEnum = CRMMenuEnum.getByAlias(paasMenuEntite.getAlias());
                paasMenuEntite.setName(menuEnum.getName());
                AccessLinkEnum accessLinkEnum = menuEnum.getAccessLinkEnum();
                paasMenuEntite.setIcon(accessLinkEnum.getIcon());
                paasMenuEntite.setEnable(EnableEnum.OPEN.getCode());
                paasMenuEntite.setColor(accessLinkEnum.getColor());
                paasMenuEntite.setUrl(accessLinkEnum.getUrl());
                paasMenuEntite.setType(menuEnum.getType());
                paasMenuEntite.setMobileUrl(accessLinkEnum.getMobileUrl());
            }
            paasMenuModel.updateBatch(paasMenuEntites,corpid);
        } catch (Exception e) {
            LOG.error("InitMarketManagementMenuHelp.Upad", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }
    /**
     * 批量添加表单
     * @date 2019/1/24 18:43
     * @param menuInitDTO
     * @param menuGroupAddBatchVO
     * @return com.xbongbong.pro.menu.pojo.vo.MenuFormAddBatchVO
     * @throws XbbException
     */
    private MenuFormAddBatchVO formAddBatch(MenuInitDTO menuInitDTO, MenuGroupAddBatchVO menuGroupAddBatchVO) throws XbbException {
        MenuFormAddBatchVO menuFormAddBatchVO;
        try {
            Long appId = menuInitDTO.getAppId();
            Map<String, PaasMenuEntity> menuMap = new HashMap<>(menuGroupAddBatchVO.getMenuList().size());
            menuGroupAddBatchVO.getMenuList().forEach((item)->{
                menuMap.put(item.getAlias(), item);
            });
            MenuFormAddBatchDTO menuFormAddBatchDTO = new MenuFormAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, menuFormAddBatchDTO);
            menuFormAddBatchDTO.setAppId(appId);
            List<MenuFormAddDTO> menuFormMenuList = new ArrayList<>();
            for(MarketManagementMenuEnum menuEnum: MarketManagementMenuEnum.values()){
                if(StringUtil.isEmpty(menuEnum.getParent())){
                    // 踢掉分组
                    continue;
                }
                MenuFormAddDTO menuFormAddDTO = new MenuFormAddDTO();
                BeanUtil.copyProperties(menuInitDTO, menuFormAddDTO);
                menuFormAddDTO.setAppId(appId);
                if(StringUtil.isEmpty(menuEnum.getParent())){
                    menuFormAddDTO.setParentId(0L);
                }else{
                    menuFormAddDTO.setParentId(menuMap.get(menuEnum.getParent()).getId());
                }
                menuFormAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                menuFormAddDTO.setAlias(menuEnum.getAlias());
                menuFormAddDTO.setName(menuEnum.getName());
                AccessLinkEnum accessLinkEnum = menuEnum.getAccessLinkEnum();
                menuFormAddDTO.setIcon(accessLinkEnum.getIcon());
                menuFormAddDTO.setColor(accessLinkEnum.getColor());
                menuFormAddDTO.setUrl(accessLinkEnum.getUrl());
                menuFormAddDTO.setMobileUrl(accessLinkEnum.getMobileUrl());
                menuFormAddDTO.setType(menuEnum.getType());
                menuFormMenuList.add(menuFormAddDTO);
            }
            menuFormAddBatchDTO.setMenuList(menuFormMenuList);
            menuFormAddBatchVO = paasMenuService.addBatchFormMenu(menuFormAddBatchDTO);
            // 将crm的产品查询改为库存查询
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.formAddBatch批量添加表单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuFormAddBatchVO;
    }

    /**
     * 批量添加分组
     * @author long.rao
     * @date 2020/11/03 18:43
     * @param menuInitDTO
     * @return com.xbongbong.pro.menu.pojo.vo.MenuGroupAddBatchVO
     * @throws XbbException
     */
    private MenuGroupAddBatchVO groupAddBatch(MenuInitDTO menuInitDTO) throws XbbException {
        MenuGroupAddBatchVO menuGroupAddBatchVO;
        try {
            Long appId = menuInitDTO.getAppId();
            MenuGroupAddBatchDTO menuGroupAddBatchDTO = new MenuGroupAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, menuGroupAddBatchDTO);
            menuGroupAddBatchDTO.setAppId(appId);
            List<MenuGroupAddDTO> groupMenuList = new ArrayList<>();
            for(MarketManagementMenuEnum menuEnum: MarketManagementMenuEnum.values()){
                if(StringUtil.isEmpty(menuEnum.getParent())){
                    MenuGroupAddDTO menuGroupAddDTO = new MenuGroupAddDTO();
                    BeanUtil.copyProperties(menuInitDTO, menuGroupAddDTO);
                    menuGroupAddDTO.setParentId(0L);
                    menuGroupAddDTO.setAppId(appId);
                    menuGroupAddDTO.setAlias(menuEnum.getAlias());
                    menuGroupAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    menuGroupAddDTO.setName(menuEnum.getName());
                    AccessLinkEnum accessLinkEnum = menuEnum.getAccessLinkEnum();
                    menuGroupAddDTO.setIcon(accessLinkEnum.getIcon());
                    menuGroupAddDTO.setColor(accessLinkEnum.getColor());
                    menuGroupAddDTO.setUrl(accessLinkEnum.getUrl());
                    menuGroupAddDTO.setMobileUrl(accessLinkEnum.getMobileUrl());
                    menuGroupAddDTO.setType(menuEnum.getType());
                    groupMenuList.add(menuGroupAddDTO);
                }
            }
            menuGroupAddBatchDTO.setMenuList(groupMenuList);
            menuGroupAddBatchVO = paasMenuService.addBatchGroupMenu(menuGroupAddBatchDTO);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.groupAddBatch批量添加分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuGroupAddBatchVO;
    }

    /**
     * 根据菜单获取表单列表
     * @param formList 表单列表
     * @param menuList 菜单列表
     * @return 返回需要插入的表单列表
     * @throws XbbException 业务异常
     */
    public List<FormEntityAddDTO> getFormList(List<FormEntityAddDTO> formList, List<PaasMenuEntity> menuList) throws XbbException{
        try {
            for (PaasMenuEntity item : menuList) {
                FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
                BeanUtil.copyProperties(item, formEntityAddDTO);
                MarketManagementMenuEnum marketManagementMenuEnum = MarketManagementMenuEnum.getByAlias(item.getAlias());
                if (Objects.isNull(marketManagementMenuEnum)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.BUSINESS_TYPE_NOT_EXIST);
                }
                // 排除客户和机会下子菜单，排除资金管理和签到，排除发票和回款
                boolean result = StringUtil.isNotEmpty(marketManagementMenuEnum.getParent());
                if(result) {
                    continue;
                }
                // if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), marketManagementMenuEnum.getCode())) {
                //     formEntityAddDTO.setName(I18nMessageUtil.getMessage(BusinessConstant.COMPANY_CUSTOMER_NAME));
                // }
                formEntityAddDTO.setBusinessType(marketManagementMenuEnum.getCode());
                formEntityAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                formEntityAddDTO.setLabels(getAppDefaultLabel(marketManagementMenuEnum.getCode()));
                formEntityAddDTO.setCustomTitle(getAppDefaultTitle(marketManagementMenuEnum.getCode()));
                formEntityAddDTO.setSummaryEntity(getAppDefaultSummary(marketManagementMenuEnum.getCode()));
                formEntityAddDTO.setBusinessRules("0");
                if(item.getParentId() == 0) {
                    formEntityAddDTO.setMenuId(item.getId());
                }else{
                    // 如果为子项，则menuId为分组的id
                    formEntityAddDTO.setMenuId(item.getParentId());
                }
                formList.add(formEntityAddDTO);
            }
        }catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.getFormList 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formList;
    }

    /**
     * 添加表单字段解释
     * @param menuInitDTO
     * @param formAddBatchVO 表单数据
     * @return 返回表单字段对象
     * @throws XbbException
     */
    public FormExplainAddBatchVO formExplainAddBatch(MenuInitDTO menuInitDTO, FormAddBatchVO formAddBatchVO) throws XbbException {
        FormExplainAddBatchVO formExplainAddBatchVO;
        try {
            List<PaasFormEntity> formResultList = formAddBatchVO.getFormList();
            FormExplainAddBatchDTO formExplainAddBatchDTO = new FormExplainAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, formExplainAddBatchDTO);
            List<FormExplainAddDTO> formExplainList = new ArrayList<>();
            for (PaasFormEntity item : formResultList) {
                FormExplainAddDTO formExplainAddDTO = new FormExplainAddDTO();
                BeanUtil.copyProperties(item, formExplainAddDTO);
                formExplainAddDTO.setFormId(item.getId());
                String alias = XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias();
                MarketManagementMenuEnum marketManagementMenuEnum = MarketManagementMenuEnum.getByAlias(alias);
                // 初始化方法获取字段列表
                List<FieldAttrEntity> explainList = new ArrayList<>();
                if (InitExplainsHelper.EMPTY_EXPLAIN.contains(item.getBusinessType())) {
                    if(Objects.nonNull(marketManagementMenuEnum)) {
                        FundSetTransitionPojo fundSetTransitionPojo = new FundSetTransitionPojo(menuInitDTO.getCorpid());
                        if(StringUtil.isNotEmpty(marketManagementMenuEnum.getParent())){
                            explainList =InitExplainsHelper.initFieldAttrEntity(marketManagementMenuEnum.getParent(),menuInitDTO.getProductForm(), fundSetTransitionPojo, DistributorMarkEnum.OTHER.getCode());
                        } else {
                            explainList = InitExplainsHelper.initFieldAttrEntity(alias,menuInitDTO.getProductForm(), fundSetTransitionPojo, DistributorMarkEnum.OTHER.getCode());
                        }
                    }
                }
                formExplainAddDTO.setFormList(explainList);
                formExplainList.add(formExplainAddDTO);
            }
            formExplainAddBatchDTO.setFormExplainList(formExplainList);
            formExplainAddBatchVO = paasFormExplainService.addBatch(formExplainAddBatchDTO);
            
            //启用客户内的关联销售线索字段
            Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid",menuInitDTO.getCorpid());
            param.put("del",0);
            param.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            List<PaasFormExplainEntity> paasFormExplainList = paasFormExplainModel.findEntitys(param);
            List<PaasFormExplainEntity> updatePaasFormExplainList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
    
            if ( CollectionsUtil.isNotEmpty(paasFormExplainList) ) {
                for ( PaasFormExplainEntity paasFormExplainEntity : paasFormExplainList ) {
                    List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                    Boolean isUpdate = false;
                    for ( FieldAttrEntity fieldAttrEntity : explainList ) {
                        if ( Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.CLUE_ID.getAttr()) && Objects.equals(fieldAttrEntity.getIsOpen(), 0) ) {
                            fieldAttrEntity.setIsOpen(1);
                            isUpdate = true;
                            break;
                        }
                    }
                    if ( isUpdate ) {
                        paasFormExplainEntity.setExplains(JSONObject.toJSONString(explainList));
                        updatePaasFormExplainList.add(paasFormExplainEntity);
                    }
                }
            }
            if ( CollectionsUtil.isNotEmpty(updatePaasFormExplainList) ) {
                paasFormExplainModel.updateBatch(updatePaasFormExplainList,menuInitDTO.getCorpid());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitMarketManagementHelp.formExplainAddBatch批量添加表单解释信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formExplainAddBatchVO;
    }
}
